//
//  SpecialDetailVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/12/29.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "SpecialDetailVC.h"
#import "SpecailGuiderIntroduceCell.h"
#import "SpecailAudioHeaderView.h"
#import "SpecialAudioCell.h"
#import "SpecialPlayVC.h"
#import "IGShare.h"
@interface SpecialDetailVC ()<UITableViewDelegate,UITableViewDataSource, SpecailAudioHeaderViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)UIImageView * specailImageView;

@property (nonatomic) NSInteger sortType;// 0 默认，1最新

@end

@implementation SpecialDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setup];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

- (void)setup {
    
    self.customBarStyle = UIStatusBarStyleLightContent;
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth /4 *3) ];
    
    _specailImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth /4 *3)];
    _specailImageView.image = [UIImage imageNamed:@"placeholder_rec"];
    [headView addSubview:_specailImageView];
    
    UIView *mengbanView = [UIView new];
    mengbanView.backgroundColor = kMengBanColor;
    [self.specailImageView addSubview:mengbanView];
    [mengbanView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.specailImageView);
    }];
    
    self.tableView.tableHeaderView = headView;
    
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    
    self.barBGAlpha = 0;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SpecailGuiderIntroduceCell" bundle:nil] forCellReuseIdentifier:@"SpecailGuiderIntroduceCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SpecialAudioCell" bundle:nil] forCellReuseIdentifier:@"SpecialAudioCell"];
    
    [self.tableView registerClass:[SpecailAudioHeaderView  class] forHeaderFooterViewReuseIdentifier:@"SpecailAudioHeaderView"];
    
    [self setAutoRowHeight:self.tableView];
    
    if (self.pageType == 1) {
        [self.specailImageView setImageURL:[NSURL URLWithString:self.special.pictureArray.firstObject] placeholderImage:kPlaceholderRec];
        [self.tableView reloadData];
        return;
    }
    
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    [NetAPIManager getLineDetailWithLinID:self.specialid block:^(LineModel *model, NSError *error) {
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        
        [self.specailImageView setImageURL:[NSURL URLWithString:model.pictureArray.firstObject] placeholderImage:kPlaceholderRec];
        self.special = model;
        [self.tableView reloadData];
    }];
    
    [self rightBarButtonWithImageName:@"分享" selector:@selector(showShareSheet:)];
}


- (void)showShareSheet:(UIButton *)sender {
    
    [self popSheet];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = self.tableView.contentOffset.y;
    CGFloat H = kScreenWidth/4 * 3;
    if (yOffset <= 0) {
        
        CGFloat factor = -yOffset + H ;
        CGRect f = CGRectMake(- (kScreenWidth * factor/H - kScreenWidth)/2, yOffset, kScreenWidth *factor/H, factor);
        self.specailImageView.frame = f;
    }
    
    if (yOffset < H - kNavigationBarHeight  ) {
        
        CGFloat aplha = yOffset /(H -kNavigationBarHeight);
        
        self.barBGAlpha = aplha;
    }else {
        self.barBGAlpha = 1;
    }
    
    if (self.barBGAlpha > 0.5) {
        self.customBarStyle = UIStatusBarStyleDefault;
    } else {
        self.customBarStyle = UIStatusBarStyleLightContent;
    }
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section == 0) {
        
        return 1;
    }else {
        
        return self.special.records.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        SpecailGuiderIntroduceCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SpecailGuiderIntroduceCell"];
        
        cell.special = self.special;
        cell.tableView = tableView;
        cell.superVC = self;
        
        return cell;
    }
    
    ScenicPoint *point = self.special.records[indexPath.row];
    
    SpecialAudioCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SpecialAudioCell"];
    cell.point = point;
    cell.model = self.special;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return nil;
        
    }

    SpecailAudioHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SpecailAudioHeaderView"];
    headerView.sortType = self.special.sortType;
    headerView.delegate = self;
    
    return headerView;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return;
        
    }
    
    SpecialPlayVC * playVC = [IGUtil loadViewController:@"SpecialPlayVC" storyboard:@"SpecialPlayVC"];
    
    playVC.lineModel = self.special;
    playVC.type = 4;
    playVC.currentScenicPoint = self.special.records[indexPath.row];
    
    [self.navigationController pushViewController:playVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        
        return 53;
    }else{
        return 0.0001f;
    }
}

#pragma mark - SpecailAudioHeaderViewDelegate
- (void)SpecailAudioHeaderTapAction:(AudioHeaderNum)type {
    
    switch (type) {
        case default_Sequence: {
            
            self.special.sortType = 0;
            NSArray *sortArray = [self.special.records sortedArrayUsingComparator:^NSComparisonResult(ScenicPoint *  _Nonnull obj1, ScenicPoint *  _Nonnull obj2) {
                
                return obj1.number.integerValue > obj2.number.integerValue;
            }];
            
            self.special.records = sortArray;
            
        }
            break;
        case last_Sequence: {
            
            self.special.sortType = 1;
            NSArray *sortArray = [self.special.records sortedArrayUsingComparator:^NSComparisonResult(ScenicPoint *  _Nonnull obj1, ScenicPoint *  _Nonnull obj2) {
                
                return obj1.createtime < obj2.createtime;
            }];
            
            self.special.records = sortArray;
            
        }
            break;
        case download_All: {
            
            if (![IGUtil hasLoginOrPresentLogin]) {
                
                return;
            }
            
            [[DownloadManager sharedManager] downloadStatusForModel:self.special block:^(MCDownloadState state, NSInteger completeCount, NSString *unionid) {
                
                if (state == MCDownloadStateCompleted) {
                    return;
                }
                [[DownloadManager sharedManager] addDownloadWithLineModel:self.special];
            }];
        }
            break;
            
        default:
            break;
    }
    
    [self.tableView reloadData];
}



#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    @weakify(self)
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    NSString * descrbe = self.special.linedesc;
    
    NSString * range = @"tourist/services/";
    NSString * str = [[AppManager sharedManager].baseURLStr substringToIndex:[AppManager sharedManager].baseURLStr.length -range.length];
    
    NSString * url = [NSString stringWithFormat:@"%@%@%@",str,@"shareh5/#/specialList?id=",self.special.lineid];
    
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        @strongify(self);
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:url title:self.special.linename descr:descrbe thumImage:self.special.pictureArray.firstObject object:self.special.playpath type:2 completion:nil];
    };
    [self.sl_popupController dismiss];
}

@end
